package com.db.deviceType.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.db.core.utils.SnowflakeIdGenerator;
import com.db.core.vo.PageResult;
import com.db.core.vo.R;
import com.db.deviceType.dto.DeviceTypePageDto;
import com.db.deviceType.mapper.DeviceTypeMapper;
import com.db.deviceType.entity.DeviceType;
import com.db.deviceType.service.DeviceTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.db.industry.entity.Industry;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.Struct;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 设备类型表 服务实现类
 * </p>
 *
 * @author db
 * @since 2023-10-30
 */
@Service
public class DeviceTypeServiceImpl extends ServiceImpl<DeviceTypeMapper, DeviceType> implements DeviceTypeService {

    @Override
    public PageResult page(DeviceTypePageDto deviceTypePageDto) {
        //获取分页信息
        Integer size = deviceTypePageDto.getSize();
        Integer now = deviceTypePageDto.getNow();
        //开始查询
        long start = (now - 1) * size;
        List<DeviceType> page = baseMapper.page(deviceTypePageDto, start);
        //查询总记录数
        long total = page.size();
        //计算总页数
        long pages = (total + size - 1) / size;
        //将数据封装到pageBean
        PageResult<DeviceType> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setPages(pages);
        pageResult.setList(page);
        return pageResult;
    }

    @Transactional
    @Override
    public R update(DeviceType deviceType) {
        deviceType.setUpdateTime(new Date());

        int i = baseMapper.updateById(deviceType);
        if (i > 0)
            return R.ok("保存成功");
        else
            return R.fail("保存失败");
    }

    @Transactional
    @Override
    public R insert(DeviceType deviceType) {
        //查询是否存在相同的设备类型
        QueryWrapper<DeviceType> deviceTypeQueryWrapper = new QueryWrapper<>();
        deviceTypeQueryWrapper.eq("device_type", deviceType.getDeviceType()).eq("name", deviceType.getName()).eq("industry_id", deviceType.getIndustry().getId());
        DeviceType deviceType1 = baseMapper.selectOne(deviceTypeQueryWrapper);
        if (!StringUtils.isEmpty(deviceType1))
            return R.fail("已存在该设备");
        deviceType.setId(SnowflakeIdGenerator.nextIdAsString());
        deviceType.setCreateTime(new Date());
        deviceType.setUpdateTime(new Date());
        baseMapper.insert(deviceType);
        return R.ok("设备添加成功");
    }
}
